/**
 * 
 */
package at.fhj.ase.generate;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import at.fhj.ase.helper.JavaGeneratorHelper;
import at.fhj.ase.shoppingcart.MCustomer;
import at.fhj.ase.shoppingcart.MProperty;
import at.fhj.ase.shoppingcart.ShoppingcartFactory;

/**
 * @author Henning
 *
 */
public class CustomerGenerator {
	private static final String CUSTOMER_TEMPLATE_FILE = "templates/CustomerTemplate.vm";
	private static final String CUSTOMER_JAVA_GENERATED = "src-gen/at/fhj/ase/Customer.java";
	private static MCustomer customer;
	static ShoppingcartFactory factory = ShoppingcartFactory.eINSTANCE;

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
	// TODO Auto-generated method stub
		customer = factory.createMCustomer();
		customer.setName("Customer");
		MProperty firstname = factory.createMProperty();
		firstname.setType(factory.createMString());
		firstname.setName("firstname");
		firstname.setWritable(true);
		MProperty lastname = factory.createMProperty();
		lastname.setType(factory.createMString());
		lastname.setName("lastname");
		lastname.setWritable(true);
		customer.getProperties().add(firstname);
		customer.getProperties().add(lastname);
		
		Velocity.init();
		VelocityContext context = new VelocityContext();
		context.put("helper", JavaGeneratorHelper.class);
		context.put("customer", customer);
		Template template = null;
		try {
			template = Velocity.getTemplate(CUSTOMER_TEMPLATE_FILE);
		}
		catch(ResourceNotFoundException resNotFoundEx){
			System.err.println(resNotFoundEx.getMessage());
		}
		catch(ParseErrorException parsErrEx) {
			System.err.println(parsErrEx.getMessage());
		}
		catch(MethodInvocationException methodInvEx) {
			System.err.println(methodInvEx.getMessage());
		}
		catch(Exception ex) {
			System.err.println(ex.getMessage());
		}
		
		StringWriter sw = new StringWriter();
		
		try{
			template.merge(context, sw);
		}
		catch(ResourceNotFoundException resNotFoundEx){
			System.err.println(resNotFoundEx.getMessage());
		}
		catch(ParseErrorException parsErrEx) {
			System.err.println(parsErrEx.getMessage());
		}
		catch(MethodInvocationException methodInvEx) {
			System.err.println(methodInvEx.getMessage());
		}
		catch(Exception ex) {
			System.err.println(ex.getMessage());
		}
		FileWriter fw = new FileWriter(CUSTOMER_JAVA_GENERATED);
		BufferedWriter bw = new BufferedWriter(fw);
		bw.append(sw.toString());
		bw.close();

	}


}
